"""
日志管理器
"""
import sys
import json
import asyncio
from typing import Dict, Any, Optional
from pathlib import Path
from loguru import logger
from config.settings import settings
from .database_log_handler import database_log_sink, init_database_logging, shutdown_database_logging


class LoggerManager:
    """日志管理器"""
    
    _loggers: Dict[str, Any] = {}  # 修复：使用 Any 而不是 logger
    _websocket_clients = set()
    _database_logging_enabled = False
    
    @classmethod
    def get_logger(cls, name: str) -> Any:  # 修复：使用 Any 而不是 logger
        """获取日志器"""
        if name not in cls._loggers:
            cls._loggers[name] = logger.bind(name=name)
        return cls._loggers[name]
    
    @classmethod
    def get_task_logger(cls, name: str, task_id: str) -> Any:
        """获取带任务ID的日志器"""
        logger_name = f"{name}_{task_id}"
        if logger_name not in cls._loggers:
            cls._loggers[logger_name] = logger.bind(name=name, task_id=task_id)
        return cls._loggers[logger_name]
    
    @classmethod
    def setup_logging(cls, enable_database: bool = True):
        """设置日志配置"""
        # 移除默认处理器
        logger.remove()
        
        # 控制台输出
        logger.add(
            sys.stdout,
            format="<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | <cyan>{extra[name]}</cyan> | <level>{message}</level>",
            level=settings.log_level,
            colorize=True
        )
        
        # 文件输出
        log_file_path = Path(settings.log_file)
        log_file_path.parent.mkdir(parents=True, exist_ok=True)
        
        logger.add(
            log_file_path,
            format="{time:YYYY-MM-DD HH:mm:ss} | {level: <8} | {extra[name]} | {message}",
            level=settings.log_level,
            rotation=settings.log_rotation,
            retention=settings.log_retention,
            encoding="utf-8"
        )
        
        # 数据库输出
        if enable_database:
            logger.add(
                database_log_sink,
                level=settings.log_level,
                serialize=True,  # 序列化record对象为JSON
                filter=lambda record: record["level"].name in ["INFO", "WARNING", "ERROR"]
            )
            cls._database_logging_enabled = True
    
    @classmethod
    async def init_database_logging(cls):
        """初始化数据库日志记录"""
        if cls._database_logging_enabled:
            await init_database_logging()
    
    @classmethod
    async def shutdown_database_logging(cls):
        """关闭数据库日志记录"""
        if cls._database_logging_enabled:
            await shutdown_database_logging()
        
       
    
    


# 初始化日志系统
LoggerManager.setup_logging()
